//
//  NewsDetailsViewController.m
//  yunyan
//
//  Created by Shui on 2018/5/3.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "NewsDetailsViewController.h"
#import "InputView.h"
#import "ShareView.h"

@interface NewsDetailsViewController ()<UIWebViewDelegate,UITableViewDataSource,UITableViewDelegate,XHInputViewDelagete>{
    
    UITableView * _tableView;
    UIWebView * _webView;
    NSMutableArray * _dataArray;
    NSMutableArray * _cellHeightArray;
    NSInteger height;
    NSDictionary * dataDic;
    int page;
    
    UIButton * likeBtn;
    UIButton * collectBtn;
}
@property (nonatomic, strong)   UIView * GRbackgView;
@property (nonatomic, strong) ShareView *shareView;

@end

@implementation NewsDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    page =1;
    _dataArray = @[].mutableCopy;
    [self customNaviItemTitle:@"新闻详情" isLeft:YES];
    [self customTabBarButtonTitle:nil image:[UIImage imageNamed:@"new_share_default"] target:self action:@selector(shareBtn) isLeft:NO];
    [self getDetailsDataRequest];
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,WIDTH,50)];
//    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    _webView.scrollView.bounces=NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.scrollEnabled = NO;
    
    [self creatTableView];
    [self getCommentListRequest];
    [self creatTextFieldView];
}

-(void)shareBtn{
    
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    
    if (user_id.length>1) {
       [self CreateShareViewAppear];
        
    }else {
        LoginViewController *loginVC = [LoginViewController new];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navc animated:YES completion:nil];
    }
  
}

-(void)CreateShareViewAppear{
    
    WeakSelf;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    _GRbackgView = [[UIView alloc] init];
    
    [self.view addSubview:_GRbackgView];
    [_GRbackgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.equalTo(weakSelf.view);
        
    }];
    
    _GRbackgView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.10];
    [self.view addSubview:_GRbackgView];
    
    _shareView = [[ShareView alloc]init];
    
    [self.view addSubview:_shareView];
    
    
    [_shareView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(weakSelf.view);
        make.height.equalTo(@200);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
    }];
    _shareView.backgroundColor = [UIColor whiteColor];
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = _shareView.frame;
        frame.origin.y = -200;
        
        [_shareView setFrame:frame];
        
        
    } completion:^(BOOL finished) {
        
    }];
    _shareView.cancelBlock = ^{
        [weakSelf geGes];
    };
    
    UITapGestureRecognizer * neargrGes=[[UITapGestureRecognizer  alloc]initWithTarget:self action:@selector(geGes)];
    [_GRbackgView addGestureRecognizer:neargrGes];
    
}



-(void)geGes{
    
    
    [UIView animateWithDuration:0.8 animations:^{
        
        
        _shareView.alpha = 0.0;
        _GRbackgView.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        
        [_shareView removeFromSuperview];
        [_GRbackgView removeFromSuperview];
        
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }];
    
}

-(void)creatTextFieldView {
    
    UIView * buttomView = [[UIView alloc] init];
    buttomView.frame = CGRectMake(0, HEIGHT - 50-SH_TopHeight, ScreenWidth, 50);
    [buttomView setViewRoundShadow];
    buttomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:buttomView];
   
    UITapGestureRecognizer * neargrGes=[[UITapGestureRecognizer  alloc]initWithTarget:self action:@selector(bottomGes)];
    [buttomView addGestureRecognizer:neargrGes];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    [buttomView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo (buttomView).offset (18.0f);
        make.width.height.equalTo (@(14.0f));
        
    }];
    imageView.image = [UIImage imageNamed:@"new_input_default"];
    UILabel * label = [[UILabel alloc]init];
    [buttomView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo (imageView.mas_right).offset (6.0f);
        make.top.bottom.equalTo (imageView);
        
    }];
    label.text = @"畅言一下...";
    label.font = [UIFont boldSystemFontOfSize:12.0];
    label.textColor = RGBA(51, 51, 51, 1);
    
}

-(void)bottomGes{
    
    [self showXHInputViewWithStyle:InputViewStyleLarge];
}

#pragma mark - XHInputViewDelagete

-(void)showXHInputViewWithStyle:(InputViewStyle)style{
    
    [InputView showWithStyle:style configurationBlock:^(InputView *inputView) {
        /** 请在此block中设置inputView属性 */
        
        /** 代理 */
        inputView.delegate = self;
        
        /** 占位符文字 */
        // inputView.placeholder = @"请输入评论文字噢噢噢噢";
        /** 设置最大输入字数 */
        inputView.maxCount = 50;
        /** 输入框颜色 */
        inputView.textViewBackgroundColor = [UIColor groupTableViewBackgroundColor];
        
        /** 更多属性设置,详见XHInputView.h文件 */
        
    } sendBlock:^BOOL(NSString *text) {
        if(text.length){
            NSLog(@"输入的信息为:%@",text);
            [self publishCommentRequestForStr:text];
            return YES;//return YES,收起键盘
        }else{
            NSLog(@"显示提示框-请输入要评论的的内容");
            SHuiMBhudTextTimeStr(@"请输入要评论的的内容");
            return NO;//return NO,不收键盘
        }
    }];
}
/** XHInputView 将要显示 */
-(void)xhInputViewWillShow:(InputView *)inputView{
    
    /** 如果你工程中有配置IQKeyboardManager,并对XHInputView造成影响,请在InputView将要显示时将其关闭 */
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
    
}

/** XHInputView 将要影藏 */
-(void)xhInputViewWillHide:(InputView *)inputView{
    
    /** 如果你工程中有配置IQKeyboardManager,并对XHInputView造成影响,请在XHInputView将要影藏时将其打开 */
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}

-(void)creatTableView {
    
    _tableView  =[[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT-SH_TopHeight-50)
                                             style:UITableViewStyleGrouped];
    _tableView.dataSource=self;
    _tableView.delegate =self;
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView =view;
    [self.view addSubview:_tableView];

    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page = 1;
        [self getCommentListRequest];
        [self getDetailsDataRequest];
        
    }];
    _tableView.mj_header = header;
    
        MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
              page++;
              [self getCommentListRequest];
        }];
    
        footer.automaticallyRefresh = YES;
        _tableView.mj_footer =footer;
        _tableView.mj_footer.hidden = NO;
}

-(void)creatWEB {
    
//    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:dataDic[@"web_view_url"]]]];
    
//     [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://hm.cdth.cn/Wap/Product/detail/id/18"]]];
    
//    NSString *BookStr = [NSString stringWithFormat:@"<html> \n"
//                         "<head> \n"
//                         "<style type=\"text/css\"> \n"
//                         "body {margin:10;font-size: %d;}\n"
//                         "</style> \n"
//                         "</head> \n"
//                         "<body>%@</body> \n"
//                         "</html>",18,dataDic[@"content"]];
//    [self.webViewloadHTMLString:BookStr baseURL:nil];
    
//    [weakSelf.webView loadHTMLString:htmlString baseURL:nil];
    
    NSString *str = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@",ScreenWidth-15,dataDic[@"content"]];
    

    
    [_webView loadHTMLString:str baseURL:nil];
   
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
//    height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] integerValue];
//    webView.frame = CGRectMake(0, 0, WIDTH,height);
    
    CGRect frame = _webView.frame;
    
    frame.size.width=ScreenWidth;
    
    frame.size.height=1;//这步不能少，不然webView.scrollView.contentSize.height为零
    
    _webView.frame= frame;
    
    frame.size.height= _webView.scrollView.contentSize.height;
    
    _webView.frame= frame;
    
   
    [_tableView reloadData];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if (section==0) {
        return 1;
    }else {
        
        return _dataArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section==0) {
        static NSString * cellId =@"cellid";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell==nil) {
            
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }else {
            
            while ([cell.contentView.subviews lastObject]) {
                
                [[cell.contentView.subviews lastObject] removeFromSuperview];
            }
        }
        
        [cell.contentView addSubview:_webView];
        
        return cell;
    }else {
        
        static NSString * cellId =@"cellid";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell==nil) {
            
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }else{
            while ([cell.contentView.subviews lastObject]) {
                
                [[cell.contentView.subviews lastObject] removeFromSuperview];
            }
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
            if (_dataArray.count>0) {
                cell.contentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
                NSDictionary * dic = _dataArray[indexPath.row];
                UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 5, WIDTH - 20, 2)];
                view.clipsToBounds = YES;
                view.layer.cornerRadius = 5.f;
                view.backgroundColor = [UIColor groupTableViewBackgroundColor];
                [cell.contentView addSubview:view];
                
                UIImageView * userImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 35, 35)];
                userImage.layer.cornerRadius = 35/2.f;
                userImage.layer.masksToBounds = YES;
                [userImage sd_setImageWithURL:[NSURL URLWithString:dic[@"head_url"]] placeholderImage:[UIImage imageNamed:@"img_head_portrait_pre"]];
                [view addSubview:userImage];
                
                
                UILabel * name =[[UILabel alloc]initWithFrame:CGRectMake(40, 10, 60, 20)];
                name.font =[UIFont systemFontOfSize:15];
                name.textColor = RGBA(26, 131, 229, 1);
                name.text =dic[@"user_nick"];
                [name sizeToFit];
                [view addSubview:name];
                
                UILabel * date =[[UILabel alloc]initWithFrame:CGRectMake(40, 34,WIDTH-70, 15)];
                date.font =[UIFont systemFontOfSize:13];
                date.textColor = [UIColor lightGrayColor];
                date.text = dic[@"create_time"];
                [view addSubview:date];
                
                
                UILabel *contentLabel;
                
                contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(40,CGRectGetMaxY(date.frame)+10 , CGRectGetWidth(view.frame)-75, 20)];
                
                contentLabel.text = dic[@"content"];
                contentLabel.textColor = [UIColor blackColor];
                contentLabel.numberOfLines = 3;
                contentLabel.font = [UIFont systemFontOfSize:18];
                [contentLabel sizeToFit];
                [view addSubview:contentLabel];
                
                    view.frame = CGRectMake(10, 5, self.view.frame.size.width - 20, CGRectGetMaxY(contentLabel.frame) + 20);
               
            }
            return cell;
     
    }
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
    
    if (section==0) {
        
        return 70;
    }else {
        
        return 120;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section==0) {
        
        return _webView.frame.size.height;
        
    }else {
        
        NSDictionary * dic = _dataArray[indexPath.row];
        
            UILabel *contentLabel;
            
            contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(40,60 , WIDTH -75, 20)];
            contentLabel.text = dic[@"content"];
            contentLabel.textColor = [UIColor blackColor];
            contentLabel.numberOfLines = 3;
            contentLabel.font = [UIFont systemFontOfSize:15];
            [contentLabel sizeToFit];
        
            return CGRectGetMaxY(contentLabel.frame)+20;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section==0) {
        
        UIView * topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 70)];
        topView.backgroundColor = [UIColor whiteColor];
        
        UILabel * titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, ScreenWidth-20, 20)];
        titleLabel.text = dataDic[@"title"];
        titleLabel.font = [UIFont boldSystemFontOfSize:16];

        [topView addSubview:titleLabel];
  
        UILabel * detailsLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(titleLabel.frame)+5, ScreenWidth-140, 20)];
        detailsLabel.text = [NSString stringWithFormat:@"来源:%@    作者:%@    %ld浏览",dataDic[@"source"],dataDic[@"author"],[dataDic[@"view_num"] integerValue]];
        detailsLabel.font = [UIFont systemFontOfSize:11];
        detailsLabel.textColor =  RGBA(136, 136, 136, 1);
        detailsLabel.numberOfLines =1;
        detailsLabel.adjustsFontSizeToFitWidth = YES;
        [topView addSubview:detailsLabel];
        
        UILabel * timeLabel  = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-120, CGRectGetMaxY(titleLabel.frame)+5,100, 20)];
        timeLabel.text = [NSString stringWithFormat:@"%@",dataDic[@"create_time"]];
        timeLabel.font = [UIFont systemFontOfSize:11];
        timeLabel.textColor =  RGBA(136, 136, 136, 1);
        timeLabel.numberOfLines =1;
        timeLabel.adjustsFontSizeToFitWidth = YES;
        [topView addSubview:timeLabel];
        
        
        return topView;
    }else {
        
        UIView * topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 120)];
        topView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        UIView * btnView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
        btnView.backgroundColor =[UIColor whiteColor];
        [topView addSubview:btnView];
        UIView * btnBageView = [[UIView alloc]initWithFrame:CGRectMake((WIDTH-200)/2, 15, 200, 40)];
        btnBageView.backgroundColor =[UIColor groupTableViewBackgroundColor];
        [btnView addSubview:btnBageView];
        btnBageView.layer.cornerRadius = 3.f;
        btnBageView.layer.masksToBounds = YES;
        
        likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        likeBtn.frame = CGRectMake(0, 0, 100, 40);
        if ([dataDic[@"is_fabulous"] integerValue]==0) {
             [likeBtn setImage:ImageName(@"new_praise_default") forState:UIControlStateNormal];

            [likeBtn setTitle:@" 点赞" forState:UIControlStateNormal];
            [likeBtn setTitleColor:RGBA(102, 102, 102, 1)forState:UIControlStateNormal];
        }else {
            
             [likeBtn setImage:ImageName(@"new_praise_pressed") forState:UIControlStateNormal];
            [likeBtn setTitle:@" 取消点赞" forState:UIControlStateNormal];
            [likeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
       
        likeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
//        [likeBtn setTitle:@" 点赞" forState:UIControlStateNormal];
//        [likeBtn setTitleColor:RGBA(102, 102, 102, 1) forState:UIControlStateNormal];
        likeBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [likeBtn addTarget:self action:@selector(likeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btnBageView addSubview:likeBtn];
        
        collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        collectBtn.frame = CGRectMake(100, 0, 100, 40);
        collectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        if ([dataDic[@"is_collection"] integerValue]==0) {
             [collectBtn setImage:ImageName(@"new_collection_default") forState:UIControlStateNormal];
            [collectBtn setTitle:@" 收藏" forState:UIControlStateNormal];
            [collectBtn setTitleColor:RGBA(102, 102, 102, 1)forState:UIControlStateNormal];
        }else {
            
            [collectBtn setImage:ImageName(@"new_collection_pressed") forState:UIControlStateNormal];
            [collectBtn setTitle:@" 取消收藏" forState:UIControlStateNormal];
            [collectBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
       

//        [collectBtn setTitleColor:RGBA(102, 102, 102, 1) forState:UIControlStateNormal];
        collectBtn.titleLabel.font = [UIFont systemFontOfSize:13];
          [collectBtn addTarget:self action:@selector(collectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btnBageView addSubview:collectBtn];
        
        
        UIImageView * hotImage =[[UIImageView alloc]initWithFrame:CGRectMake((WIDTH-144)/2, 75, 144, 30)];
        hotImage.image = ImageName(@"new_title_pressed");
        [topView addSubview:hotImage];
        
        return topView;
    }
}

-(void)likeBtnClick:(UIButton *)btn{
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
         [self setLikeRequest];
    }else {
        
         LoginViewController *loginVC = [LoginViewController new];
          UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
                        [self presentViewController:navc animated:YES completion:nil];
    }
    
}

-(void)collectBtnClick:(UIButton *)btn{
    
   NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>0||user_id!=nil) {
         [self setCollectRequest];
    }else {
        
        LoginViewController *loginVC = [LoginViewController new];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navc animated:YES completion:nil];
    }
}


-(void)getDetailsDataRequest{
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    
    if (user_id.length>1) {
        
    }else {
        
        user_id = @"";
    }
    
    NSDictionary * dic = @{@"user_id":user_id,
                           @"news_id":self.news_idStr
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(news_details_api) andparameters:dic Success:^(id responseObject) {
        
        dataDic = responseObject;
        
        NSArray * imageArray = [self filterImage:dataDic[@"content"]];
        
        if (imageArray.count==0) {
            
            USER_DEFAULTSet(@"http://a1.qpic.cn/psb?/V147v55d35m6eX/xXdZ2De4s1iE5gYJaikuWyqltDsmFf*LHHZ1ANFPtso!/m/dDABAAAAAAAA&bo=eAB4AAAAAAADByI!&rf=photolist", @"shareImage");
        }else {
            USER_DEFAULTSet(imageArray[0], @"shareImage");
        }
        
        NSString * contentStr = [self getZZwithString:dataDic[@"content"]];
//        @"type":USER_DEFAULTGet(@"shareType"),
//        @"news_id":USER_DEFAULTGet(@"shareNewsId")
        
        NSString * newsId= [NSString stringWithFormat:@"%ld",[dataDic[@"id"] integerValue]];
        USER_DEFAULTSet(newsId,@"shareNewsId");
         USER_DEFAULTSet(@"1",@"shareType");
        USER_DEFAULTSet(dataDic[@"title"], @"shareTitle");
        USER_DEFAULTSet(contentStr, @"shareContent");
        USER_DEFAULTSet(dataDic[@"share_url"], @"shareUrl");
        
        [self creatWEB];
        [_tableView reloadData];
    } failed:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

//正则去除网络标签
-(NSString *)getZZwithString:(NSString *)string{
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n|&nbsp"
                                                                                    options:0
                                                                                      error:nil];
    string=[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    return string;
}


// 从html中获取图片
-(NSArray *)filterImage:(NSString *)html
{
    NSMutableArray *resultArray = [NSMutableArray array];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|></img>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
    
    for (NSTextCheckingResult *item in result) {
        NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
        
        NSArray *tmpArray = nil;
        if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
            tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
        } else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
            tmpArray = [imgHtml componentsSeparatedByString:@"src="];
        }
        
        if (tmpArray.count >= 2) {
            NSString *src = tmpArray[1];
            
            NSUInteger loc = [src rangeOfString:@"\""].location;
            if (loc != NSNotFound) {
                src = [src substringToIndex:loc];
                [resultArray addObject:src];
            }
        }
    }
    
    return resultArray;
}

-(void)refreshDetailsDataRequest{
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
       
    }else {
        
        user_id = @"";
//        LoginViewController *loginVC = [LoginViewController new];
//        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
//        [self presentViewController:navc animated:YES completion:nil];
    }
    
    NSDictionary * dic = @{@"user_id":user_id,
                           @"news_id":self.news_idStr
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(news_details_api) andparameters:dic Success:^(id responseObject) {
        
        dataDic = responseObject;
        
//        [self creatWEB];
//        [_tableView reloadData];
    } failed:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

-(void)getCommentListRequest{
    
    NSDictionary * dic = @{@"news_id":self.news_idStr,
                           @"page":[NSString stringWithFormat:@"%d",page],
                           @"type":@"1"
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_commentList_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray * array = responseObject;
            
            if (page == 1) {
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }else {
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }
            
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            NSLog(@"没有数据");
        }else {
            SHuiMBhudTextTimeStr(@"请稍后再试");
        }
    }];
    
}

//设置喜欢
-(void)setLikeRequest{
    
    NSString * operation;
    
   
    int sele = [dataDic[@"is_fabulous"] intValue];
    if (sele == 0) {
        operation = @"1";
    }else {
        
        operation = @"2";
    }
    
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"token":USER_DEFAULTGet(@"token"),
                           @"news_id":self.news_idStr,
                           @"operation":operation,
                           @"type":@"1"
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(collect_api) andparameters:dic Success:^(id responseObject) {
        
        [self refreshDetailsDataRequest];
        
        if (sele ==0) {
            
            [likeBtn setImage:ImageName(@"new_praise_pressed") forState:UIControlStateNormal];
            [likeBtn setTitle:@" 取消点赞" forState:UIControlStateNormal];
            [likeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
           
        }else {
            
            [likeBtn setImage:ImageName(@"new_praise_default") forState:UIControlStateNormal];
            [likeBtn setTitle:@" 点赞" forState:UIControlStateNormal];
            [likeBtn setTitleColor:RGBA(102, 102, 102, 1)forState:UIControlStateNormal];
        }
     
        //        [_activeDetailTab reloadData];
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
     
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            
            SHuiMBhudTextTimeStr(@"文章不存在");
        }else if(responses.statusCode == 403){
            SHuiMBhudTextTimeStr(@"已经点赞");
        }else if(responses.statusCode == 500){
            SHuiMBhudTextTimeStr(@"点赞失败");
        }else {
            SHuiMBhudTextTimeStr(@"请稍后再试");
        }
    }];
    
}

//设置收藏
-(void)setCollectRequest{
    
    NSString * operation;
    
    int sele = [dataDic[@"is_collection"] intValue];
    if (sele == 0) {
        operation = @"1";
    }else {
        
        operation = @"2";
    }
    NSDictionary * dic = @{@"news_id":self.news_idStr,
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"token":USER_DEFAULTGet(@"token"),
                           @"operation":operation,
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(news_setCollect_api) andparameters:dic Success:^(id responseObject) {
        
         [self refreshDetailsDataRequest];
        
        if (sele==0) {
            
            [collectBtn setImage:ImageName(@"new_collection_pressed") forState:UIControlStateNormal];
            [collectBtn setTitle:@" 取消收藏" forState:UIControlStateNormal];
            [collectBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
       
            
        }else {
            
            [collectBtn setImage:ImageName(@"new_collection_default") forState:UIControlStateNormal];
            [collectBtn setTitle:@" 收藏" forState:UIControlStateNormal];
            [collectBtn setTitleColor:RGBA(102, 102, 102, 1) forState:UIControlStateNormal];
        }
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
     
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            
            SHuiMBhudTextTimeStr(@"文章不存在");
        }else if(responses.statusCode == 403){
            SHuiMBhudTextTimeStr(@"已经收藏");
        }else if(responses.statusCode == 500){
            SHuiMBhudTextTimeStr(@"收藏失败");
        }else {
            SHuiMBhudTextTimeStr(@"请稍后再试");
        }
    }];
    
}

// 发布评论
-(void)publishCommentRequestForStr:(NSString *)str{
    
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
        NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                               @"news_id":self.news_idStr,
                               @"mac_code":[SHJudgeTools getDeviceId],
                               @"token":USER_DEFAULTGet(@"token"),
                               @"type":@"1",
                               @"content":str
                               };
        
        [PostNetWorking postNetWorkingStr:RequestUrlStr(publish_comment_api) andparameters:dic Success:^(id responseObject) {
            
            SHuiMBhudTextTimeStr(@"发送成功！");
            page =1;
            [self getCommentListRequest];
            [_tableView reloadData];
        } failed:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            
            if (responses.statusCode == 404) {
                SHuiMBhudTextTimeStr(@"未获取到数据");
            }else if (responses.statusCode==403){
                SHuiMBhudTextTimeStr(@"评论1分钟内只能提交一次");
            }else {
                SHuiMBhudTextNetError;
            }
        }];
    }else {
                LoginViewController *loginVC = [LoginViewController new];
                UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
                [self presentViewController:navc animated:YES completion:nil];
    }
    
}


@end
